package com.youkeda.meetingroom.auth;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Calendar;
import java.util.Date;

/**
 * JwtUtil的注释
 *
 * @author: Awake
 * @date: 2019-07-13 22:16
 **/
public class JWTUtil {

    private static Algorithm algorithm = Algorithm.HMAC256("secret");

    public static String generator(String userId) {
        //过期信息
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DAY_OF_YEAR, 3);
        Date expireDate = calendar.getTime();

        try {
            //创建一个Token 包含用户id信息
            String token = JWT.create()
                    .withIssuer("youkeda")
                    .withClaim("userId",userId)
                    .withExpiresAt(expireDate)
                    .sign(algorithm);
            return token;
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 解析
     *
     * @param token
     */
    public static String parse(String token) {
        JWTVerifier verifier = JWT.require(algorithm).withIssuer("youkeda").build();
        DecodedJWT decodedJWT = verifier.verify(token);
        String userId = decodedJWT.getClaim("userId").asString();
        return userId;
    }

    public static void main(String[] args) {
        String token = generator("id345");
        System.out.println(token);
    }
}
